package com.train.mgr.config.secrity.components;

import com.train.common.enums.LoginTypeEnum;
import com.train.common.model.SysUser;
import com.train.mgr.modules.system.entity.User;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;


public class TrainAuthenticationProvider implements AuthenticationProvider {
    //校验用户的业务service
    private UserDetailsServiceImpl userDetailsService;


    @Override
    //具体认证逻辑
    public Authentication authenticate(Authentication authentication) {
        TrainAuthenticationToken authenticationToken = (TrainAuthenticationToken) authentication;
        String userName = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        Integer userType = authenticationToken.getUserType();
        String openId = authenticationToken.getOpenId();
        String token = authenticationToken.getToken();
        LoginTypeEnum loginType = authenticationToken.getLoginType();
        User user = null;
        //业务类认证
        if (loginType.getLoginType().equals(LoginTypeEnum.WECHATLOGIN.getLoginType())){
            user = getUserDetailsService().loginByWechat(openId ,userType);
        }
        if (loginType.getLoginType().equals(LoginTypeEnum.USERNAMELOGIN.getLoginType())){
            user = getUserDetailsService().loginByUserNamePassword(userName ,password ,userType);
        }


        if (user == null) {
            throw new InternalAuthenticationServiceException("验证失败");
        }
        UserDetails userDetails = userDetailsService.findPermission(user);

        //认证完成填充Authentication，这里将user赋值给principal，复用了这个字段
        TrainAuthenticationToken authenticationResult = new TrainAuthenticationToken(userDetails, null ,userType,openId,user.getId().toString(),token,userDetails ==null ? AuthorityUtils.NO_AUTHORITIES : userDetails.getAuthorities());
        
        //details可以保存额外的信息，是父类的字段，这里保存的是租户信息
        //authenticationResult.setDetails(user.getTenantInfo());
        return authenticationResult;
    }

    @Override
    //指定具体的Authentication
    //根据你指定的Authentication来找到具体的Provider
    public boolean supports(Class<?> authentication) {
        return TrainAuthenticationToken.class.isAssignableFrom(authentication);
    }
    
    public void setUserDetailsService(UserDetailsServiceImpl userDetailsService) {
		this.userDetailsService = userDetailsService;
    }

    protected UserDetailsServiceImpl getUserDetailsService() {
            return userDetailsService;
    }

}

